<template>
    <div class="container">
        <div class="left">
            <div class="download-tab">
                <h2 class="title">列表选择</h2>
                
                <div class="form-section">
                    <div class="form-item">
                        <label class="form-label">产品列表</label>
                        <a-select
                            v-model="projectListValue"
                            size="small"
                            placeholder="请选择"
                            style="width: 100%;"
                            @change="handleProductSelChange"
                        >
                            <a-select-option
                                v-for="item in projectOptions"
                                :key="item"
                                :value="item"
                            >
                                {{ item }}
                            </a-select-option>
                        </a-select>
                    </div>

                    <div class="form-item">
                        <label class="form-label">设备列表</label>
                        <a-select
                            v-model="deviceListValue"
                            size="small"
                            placeholder="请选择"
                            style="width: 100%;"
                        >
                            <a-select-option
                                v-for="item in deviceOptions"
                                :key="item"
                                :value="item"
                            >
                                {{ item }}
                            </a-select-option>
                        </a-select>
                    </div>

                    <div class="form-item">
                        <label class="form-label">透传端口</label>
                        <a-select
                            v-model="portValue"
                            size="small"
                            show-search
                            allow-clear
                            placeholder="请选择"
                            :disabled="isDisabled"
                            style="width: 100%;"
                            @change="handleSelectPortType"
                        >
                            <a-select-option
                                v-for="item in portsTypes"
                                :key="item"
                                :value="item"
                            >
                                {{ item }}
                            </a-select-option>
                        </a-select>
                    </div>

                    <div class="form-item">
                        <label class="form-label">透传方式</label>
                        <a-select
                            v-model="downloadTypeValue"
                            size="small"
                            placeholder="请选择"
                            :disabled="isSelectDisabled"
                            style="width: 100%;"
                            @change="handleSelectDownloadType"
                        >
                            <a-select-option
                                v-for="item in downloadTypes"
                                :key="item.value"
                                :value="item.value"
                            >
                                {{ item.label }}
                            </a-select-option>
                        </a-select>
                    </div>
                </div>

                <div class="connection-section">
                    <SerialPortSetting
                        v-if="downloadTypeValue === 'serial'"
                        ref="SPSetting"
                        @isConnect="handleSerialConnect"
                    />
                    <NetworkSetting
                        v-if="downloadTypeValue === 'network'"
                        ref="NetSetting"
                        :address-value="netAddress"
                        :port-value="netPort"
                        :net-adapters-value="netAdapters"
                        :net-adapter-i-p-value="netAdaptersIp"          
                        @isConnect="handleNetConnect"
                    />
                </div>

                <div class="form-item">
                    <a-button 
                        type="primary" 
                        size="default"
                        @click="handleTrans"
                    >
                        {{ transButtonText }}
                    </a-button>
                </div>
            </div>
        </div>

        <div class="middle" />

        <div class="right">
            <DeviceList ref="DevList" />
        </div>

        <a-modal 
            title="透传状态" 
            :visible="transDialogVisible" 
            width="400px" 
            :footer="null"
            :closable="false"
            :mask-closable="false"
        >
            <div class="trans-status-content">
                <div class="loading-section">
                    <a-spin size="large" />
                    <p class="loading-text">正在拼命透传中...</p>
                </div>
                <div class="stop-section">
                    <a-button 
                        type="danger" 
                        size="large"
                        @click="handleTransClose"
                    >
                        停止透传
                    </a-button>
                </div>
            </div>
        </a-modal>
    </div>
</template>
  
<script>
import SerialPortSetting from '@/components/DownloadTab/SerialPortSetting.vue'
import NetworkSetting from '@/components/DownloadTab/NetworkSetting.vue'
import DeviceList from '@/components/DownloadTab/DeviceList.vue'
import DownloadTabManager from '@/api/TabManager/DownloadTabManager'

export default {
    name: 'RemoteTrans',
    components: {
        SerialPortSetting,
        NetworkSetting,
        DeviceList
    },
    data() {
        return {
            downloadTabManager: new DownloadTabManager(),
            projectOptions: [],
            deviceOptions: [],
            projectListValue: '',
            deviceListValue: '',
            downloadTypeValue: 'network',
            downloadTypes: [
                {
                    label: '串口',
                    value: 'serial'
                },
                {
                    label: '网口',
                    value: 'network'
                }
            ],
            transServeValue: 'websocket',
            netTransServes: [
                {
                    value: 'websocket',
                    label: 'websocket'
                },
                {
                    value: 'ssh',
                    label: 'ssh'
                }        
            ],     
            isDisabled: false,
            serialPortData: [],
            targetPortData: [],
            netAddress: '',
            netPort: '',
            netAdapters: [],
            netAdaptersIp: [],  
            transButtonText: '开始透传',
            isTrans: false,
            isTransAbnormal: false,
            transDialogVisible: false,
            portValue: '',
            portsTypes: [],
            isPortTypeDisabled: false
        }
    },
    computed: {
        isSelectDisabled() {
            return this.isDisabled || this.isPortTypeDisabled
        }
    },
    created() {
    
    },

    mounted() {
        this.loadProductList()
    },
    methods: {
        // 加载产品列表
        async loadProductList() {
            this.$message.loading('正在加载产品列表...', 0)
            try {
                const res = await this.downloadTabManager.getProductList()
                this.projectOptions = []
                this.projectListValue = ''
                if (res.code === 0) {
                    this.projectOptions = JSON.parse(res.data)
                    if (this.projectOptions.length > 0) {
                        this.projectListValue = this.projectOptions[0]
                    }
                    this.loadDeviceList()
                    this.loadTransPorts()
                    this.$message.destroy()
                } else {
                    this.$message.destroy()
                    console.error('❌ [DownloadTab] 加载产品列表失败:', res.msg)
                    // 需要弹出错误并提示用户退出并重新登录
                    this.$message.error(res.msg + '，登录已过期，请重新登录')
                    this.$router.push('/login')
                }
            } catch (error) {
                this.$message.destroy()
                console.error('❌ [DownloadTab] 加载产品列表失败:', error)
                this.$message.error('加载产品列表失败: ' + (error.message || '未知错误'))
            }
        },

        // 加载设备列表
        async loadDeviceList() {
            try {
                const res = await this.downloadTabManager.getDeviceList(this.projectListValue)  
                console.log('🔍 [DownloadTab] 加载设备列表:', res)
                this.deviceOptions = []
                this.deviceListValue = ''
                if (res.code === 0) {
                    this.deviceOptions = JSON.parse(res.data)
                    if (this.deviceOptions.length > 0) {
                        this.deviceListValue = this.deviceOptions[0]
                    }
                } else {
                    console.error('❌ [DownloadTab] 加载设备列表失败:', res.msg)
                    this.$message.error(res.msg)
                }
                this.loadDeviceDetailList()
            } catch (error) {
                console.error('❌ [DownloadTab] 加载设备列表失败:', error)
                this.$message.error('加载设备列表失败: ' + (error.message || '未知错误'))
            }
        },

        // 加载透传端口
        async loadTransPorts() {
            try {
                const res = await this.downloadTabManager.getTransPorts(this.projectListValue)
                console.log('🔍 [DownloadTab] 加载透传端口:', res)
                if (res.code === 0) {
                    this.portsTypes = JSON.parse(res.data)
                    if (this.portsTypes.length > 0) {
                        this.portValue = this.portsTypes[0]
                        this.handleSelectPortDisabled(this.portValue)
                        this.handleSelectPortType(this.portValue)
                    }
                } else {
                    console.error('❌ [DownloadTab] 加载透传端口失败:', res.msg)
                    this.$message.error(res.msg)
                }
            } catch (error) {
                console.error('❌ [DownloadTab] 加载透传端口失败:', error)
                this.$message.error('加载透传端口失败: ' + (error.message || '未知错误'))
            }
        },

        // 加载详细设备列表
        async loadDeviceDetailList() {
            try {
                const res = await this.downloadTabManager.getDeviceDetailList(this.projectListValue)
                console.log('🔍 [DownloadTab] 加载详细设备列表:', res)
                if (res.code === 0) {
                    this.deviceDetailList = JSON.parse(res.data)
                    this.$refs.DevList.updateDeviceList(this.deviceDetailList)
                } else {
                    console.error('❌ [DownloadTab] 加载详细设备列表失败:', res.msg)
                    this.$message.error(res.msg)
                }
            } catch (error) {
                console.error('❌ [DownloadTab] 加载详细设备列表失败:', error)
                this.$message.error('加载详细设备列表失败: ' + (error.message || '未知错误'))
            }
        },

        // 处理网卡切换 (全局设置)
        handleGlobalNicChange(selectedNicId) {
            console.log('🔄 [DownloadTab] 全局网卡切换:', selectedNicId)
            
            const selectedAdapter = this.netAdapters.find(adapter => adapter.id === selectedNicId)
            if (!selectedAdapter) {
                console.warn('⚠️ [DownloadTab] 未找到选中的网卡')
                return
            }
            
            // 更新全局可用IP列表
            this.netAdaptersIp = selectedAdapter.ipAddresses.length > 0 
                ? selectedAdapter.ipAddresses 
                : ['0.0.0.0']
            console.log('✅ [DownloadTab] 全局IP已更新:', this.netAdaptersIp)
        },

        handleProductSelChange(value) {
            console.log('handleProductSelChange', value)
            this.loadDeviceList()
        },

        handleSelectDownloadType(value) {
            console.log('Selected value:', value)
            this.downloadTypeValue = value
            this.$nextTick(() => {
                if (value === 'network') {
                    if (this.$refs.NetSetting) {
                        this.$refs.NetSetting.updateInterfaces(this.netAdapters)
                        this.$refs.NetSetting.updateInterfaceIPs(this.netAdaptersIp)
                    }    
                } else {
                    if (this.$refs.SPSetting) {
                        this.$refs.SPSetting.loadSerialPorts()
                        // remoteTrans.onGetTargetPort()
                    }    
                }        
            })      
        },

        async handleSerialConnect(isDisabled, value) {
            this.isDisabled = isDisabled
            console.log('🔍 [DownloadTab] 串口连接:', value)

            try {
                const res = await this.downloadTabManager.connectSerial(value)
                if (res.code === 0) {
                    if (this.isDisabled) {
                        this.$message.success('串口连接成功')
                    } else {
                        this.$message.success('串口关闭成功')
                    }
                } else {
                    this.$refs.SPSetting.updateStatus('False')
                    this.$message.error(res.msg)
                    this.isDisabled = false
                }
                console.log('🔍 [DownloadTab] 串口连接:', res)
            } catch (error) {
                console.log('🔍 [DownloadTab] 串口连接失败:', error)
                this.$refs.SPSetting.updateStatus('False')
                this.isDisabled = false
                if (this.isDisabled) {
                    this.$message.error('串口连接失败' + error.message)
                } else {
                    this.$message.error('串口关闭失败' + error.message)
                }
            }
        },

        async handleNetConnect(isDisabled, netAddress, netPort, plc_address, plc_port) {
            console.log('handleNetConnect', netAddress, netPort, isDisabled, plc_address, plc_port)
            this.netAddress = netAddress
            this.netPort = netPort
            this.isDisabled = isDisabled

            try {
                const params = {
                    netAddress: netAddress,
                    netPort: netPort,
                    plcAddress: plc_address,
                    plcPort: plc_port
                }
                const res = await this.downloadTabManager.connectNetwork(JSON.stringify(params))
                if (res.code === 0) {
                    if (this.isDisabled) {
                        this.$message.success('网口连接成功')
                    } else {
                        this.$message.success('网口关闭成功')
                    }
                } else {
                    this.$refs.NetSetting.updateStatus('False')
                    this.$message.error(res.msg)
                    this.isDisabled = false
                }
            } catch (error) {
                if (this.isDisabled) {
                    this.$message.error('网口连接失败' + error.message)
                } else {
                    this.$message.error('网口关闭失败' + error.message)
                }
                this.$refs.NetSetting.updateStatus('False')
                this.isDisabled = false
            }
        },

        async handleTrans() {
            console.log('handleTrans')
            this.isTrans = !this.isTrans
            this.transButtonText = '开始透传'
            if (this.isTrans) {
                this.transButtonText = '停止透传'
                this.transDialogVisible = true
            } else {
                this.transDialogVisible = false
            }
            if (!this.isTransAbnormal) {
                try {
                    // 需要获取选中产品和设备信息
                    const params = {
                        project: this.projectListValue,
                        device: this.deviceListValue,
                        port: this.portValue,
                        type: this.downloadTypeValue
                    }
                    const res = await this.downloadTabManager.startTransmission(JSON.stringify(params))
                    if (res.code === 0) {
                        this.$message.success('透传开始')
                    } else {
                        // 失败后，需要关闭loading
                        this.$message.destroy()
                        this.transDialogVisible = false
                        this.$message.error(res.msg)
                    }
                } catch (error) {
                    this.$message.error('透传失败' + error.message)
                    this.isTransAbnormal = true
                }
            } 
            this.transButtonText = '开始透传'
            this.isTransAbnormal = false
        },

        async handleTransClose() {
            this.$confirm({
                title: '确认关闭？',
                content: '确认要关闭透传吗？',
                onOk: async() => {
                    this.transDialogVisible = false
                    this.isTrans = !this.isTrans
                    this.transButtonText = '开始透传' 
                    if (!this.isTransAbnormal) {
                        // 需要获取选中产品和设备信息
                        const params = {
                            project: this.projectListValue,
                            device: this.deviceListValue,
                            port: this.portValue,
                            type: this.downloadTypeValue
                        }
                        const res = await this.downloadTabManager.startTransmission(JSON.stringify(params))
                        if (res.code === 0) {
                            this.$message.success('透传关闭')
                        } else {
                            this.$message.error(res.msg)
                        }
                    }  
                    this.isTransAbnormal = false
                },
                onCancel() {}
            })
        },

        updateTransStatus(bTrans) {
            if (bTrans === 'False') {
                this.loading = false
                this.isTrans = !this.isTrans
                this.transButtonText = '开始透传'
                this.$message.destroy()
                this.transDialogVisible = false
                this.isTransAbnormal = true
                this.$notification.warning({
                    message: '警告',
                    description: '链接透传服务器失败'
                })
            }
        },

        handleSelectPortType(value) {
            this.handleSelectPortDisabled(value)
        },

        handleSelectPortDisabled(value) { 
            console.log('handleSelectPortDisabled', value)
            // let isDefault = false
            // this.portsTypes.forEach(item => {
            //     if (item === value) {
            //         isDefault = true
            //     }
            // }) 
            // this.isPortTypeDisabled = isDefault    先屏蔽  
        },
 
        handleSelectNetworkPort(value) {
            this.$nextTick(() => {
                if (this.$refs.NetSetting) {
                    this.$refs.NetSetting.updatePorts(value)
                }                
            })      
        }, 

        handleSelectSerialPort(value) {
            this.$nextTick(() => {
                if (this.$refs.SPSetting) {          
                    this.$refs.SPSetting.updatePorts(value)
                }                
            })      
        }

    }  
}
</script>
  
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.container {
    display: flex;
}
.left {
    flex: 0 0 34%; /* 占据30%的宽度 */
    padding: 10px;
}
.middle {
    flex: 0 0 1%; /* 占据50%的宽度 */
    padding: 1px;
}
.right {
    flex: 0 0 65%; /* 占据20%的宽度 */
    padding: 10px;
}
.download-tab {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    max-width: 600px;
    margin: 0 auto;
}
.title {
    text-align: left;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
}
.form-section {
    margin-bottom: 20px;
}
.connection-section {
    margin-bottom: 20px;
}
.form-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}
.form-label {
    width: 80px;
    text-align: right;
    margin-right: 15px;
    font-size: 14px;
    color: #333;
    flex-shrink: 0;
}
.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
}

// 覆盖 Ant Design 的默认样式
:deep(.ant-select) {
    flex: 1;
}
:deep(.ant-input) {
    flex: 1;
}

// 透传状态提示框样式
.trans-status-content {
    text-align: center;
    padding: 20px 0;
}
.loading-section {
    margin-bottom: 30px;
    .loading-text {
        margin-top: 16px;
        font-size: 16px;
        color: #666;
        margin-bottom: 0;
    }
}
.stop-section {
    .ant-btn {
        min-width: 120px;
        height: 40px;
        font-size: 16px;
    }
}
</style>
  